<template>
    <div>
        <!-- KPI 数据 -->
        <el-row :gutter="20">
            <el-col :span="8">
                <KpiCard title="当月缴纳企业数" icon="office-building" :value="enterpriseNumber" />
            </el-col>
            <el-col :span="8">
                <KpiCard title="参保人数" icon="user" :value="peopleNumber" />
            </el-col>
            <el-col :span="8">
                <KpiCard title="当月缴费总额" icon="money" :value="payNumber" unit="元" />
            </el-col>
        </el-row>

        <!-- 图表区域 -->
         <!-- 折线图 -->
        <el-row :gutter="20" class="mt-4">
            <el-col :span="12">
                <el-card>
                    <div>缴费情况</div>
                    <!-- 筛选 -->
                    <el-select v-model="selectedRange"  style="width: 120px" @change="onRangeChange">
                            <el-option label="近3个月" value=3 />
                            <el-option label="近6个月" value=6 />
                            <el-option label="近12个月" value=12 />
                        </el-select>
                    <Chart :option="lineOption" height="300px" />
                </el-card>
            </el-col>
            <!-- 柱状图 -->
            <el-col :span="12">
                <el-card>
                    <div class="text-lg font-semibold mb-2">各企业缴费对比</div>
                    <div class="datepicker">
                        <el-date-picker v-model="selectedMonth" @change="onDateChange" type="year"
                            placeholder="选择日期" value-format="YYYY-MM">
                        </el-date-picker>
                    </div>
                    <Chart :option="barOption" height="300px" />
                </el-card>
            </el-col>
        </el-row>
    </div>
</template>

<script setup>
import Chart from '@/components/Chart.vue'
import KpiCard from '@/components/KpiCard.vue'
import request from '@/utils/request'
import { ElMessage } from 'element-plus'
import { ref } from 'vue'

// KPI 数据
const enterpriseNumber = ref(0) // 企业数量 
const peopleNumber = ref(0) // 参保人数
const payNumber = ref(0) // 缴费总额
const nowYear = new Date().getFullYear() // 当前年份
const nowMonth = (new Date().getMonth() + 1).toString().padStart(2, '0'); // 当前月份，确保两位数
// 计算当前年份和月份
const currentDate= ref(`${nowYear}-${nowMonth}`) // 当前日期
// 获取数据
const fetchKpiData = () => {
    request.get('/enterprise/kpi', {
    params: { month: currentDate.value }}).then(res => {
        if (res.code !== "200") {
            ElMessage.error('获取数据失败')
            return
        }
        //解构赋值并重命名
        const { enterpriseNumber: entNum, peopleNumber: peoNum, payNumber: payNum } = res.data
        enterpriseNumber.value = entNum
        peopleNumber.value = peoNum
        payNumber.value = payNum
    })
}
fetchKpiData() // 初始加载一次



// 柱状图配置
const selectedMonth = ref(nowYear) // 默认年份
const enterprises = ref([]) // 企业名称数组
const amounts = ref([]) // 企业缴费金额数组
const barOption = ref({
    title: {
        text: `${selectedMonth.value+"年"} 各企业缴费对比`,
        left: 'center'
    },
    tooltip: { trigger: 'axis' },
    xAxis: {
        type: 'category',
        data: [],
    },
    yAxis: {
        type: 'value',
        name: '缴费金额（元）'
    },
    dataZoom: [
    {
      type: 'slider',
      show: true,
      start: 0,
      end: 100,
      height: 20,
      bottom: 0
    }
  ],
    series: [
        {
            name: '缴费金额',
            type: 'bar',
            data: [],
            itemStyle: { color: '#67C23A' }
        }
    ]
})
// 获取柱状图数据
const fetchBarData = () => {
    request.get('/pension/compare', {
        params: { month: selectedMonth.value }
    }).then(res => {
        if (res.code !== "200") {
            ElMessage.error('获取企业对比数据失败')
            return
        }
        enterprises.value = res.data.map(item => item.enterprise)
        amounts.value = res.data.map(item => item.amount)
        // 更新图表配置
        barOption.value = {
            ...barOption.value,
            title: {
                ...barOption.value.title,
                text: `${selectedMonth.value} 各企业缴费对比`
            },
            xAxis: {
                ...barOption.value.xAxis,
                data: enterprises.value
            },
            series: [
                {
                    ...barOption.value.series[0],
                    data: amounts.value
                }
            ]
        }
    })
}
// 初始加载一次
fetchBarData()
// 监听月份变化时更新图表数据
const onDateChange = () => {
    fetchBarData()
}


// 折线图图表配置
const lineOption = ref({})
const selectedRange = ref()// 当前筛选月份
// 获取图表数据
const fetchLineData = () => {
    request.get('/pension/paymentTrend', {
        params: { months: selectedRange.value }
    }).then(res => {
        if (res.code !== "200") {
            ElMessage.error('获取图表数据失败')
            return
        }
        const { months, amounts } = res.data
        lineOption.value = {
            tooltip: { trigger: 'axis' },
            xAxis: { type: 'category', data: months },
            yAxis: { type: 'value', name: '单位：元' },
            series: [{
                name: '缴费金额',
                type: 'line',
                smooth: true,
                data: amounts,
                lineStyle: { color: '#409EFF' },
                itemStyle: { color: '#409EFF' }
            }]
        }
    })
}
// 首次加载时获取默认数据
fetchLineData()
// 监听下拉选项变更时更新图表
const onRangeChange = () => {
    fetchLineData()
}


</script>

<style scoped>
.mt-4 {
    margin-top: 20px;
}

.datepicker {
    margin-bottom: 10px;
    width: 60px;
}
</style>